/*
 *    Copyright 2011-2012 The Hook Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.hook.yaksha.node.component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hook.yaksha.config.Config;
import org.hook.yaksha.exception.AnalysisException;
import org.hook.yaksha.node.Node;
import org.hook.yaksha.node.NodeEvent;

/**
 * 抽象节点处理主骨骼结构，当前节点循环执行某一些逻辑，后台也支持监听事件发生
 * 
 * @author suwuqiang 2011-12-28
 */
public abstract class AbstractNode<E extends NodeEvent, C extends Config> implements Node<E, C> {
	private static final Log logger = LogFactory.getLog(AbstractNode.class);
	private BlockingQueue<E> queue;
	private Inspector inspector;
	private Thread innerThread;
	protected C config;
	volatile boolean running = true;

	public AbstractNode() {
		queue = new LinkedBlockingQueue<E>(); // 消息队列
		inspector = new Inspector(); // 后台监控者，用来接受事件，处理外部消息
		inspector.start();
	}

	@Override
	public void startNode() {
		innerThread = new Thread(this);
		innerThread.start();
	}

	@Override
	public void stopNode() {
		running = false;
		innerThread.interrupt();
	}

	public C getConfig() {
		return config;
	}

	public void setConfig(C config) {
		this.config = config;
	}

	@Override
	public void run() {
		try {
			this.init();
			while (running) {
				try {
					process();
				} catch (Exception ex) {
					logger.error(ex, ex);
				}
			}
		} catch (AnalysisException ex) {
			logger.error(ex, ex);
		} finally {
			this.inspector.stopInspector();
			this.releaseResource();
			logger.info("Node stopped ...");
		}
	}

	@Override
	public boolean addEvent(E event) {
		return queue.offer(event);
	}

	private class Inspector extends Thread {
		@Override
		public void run() {
			while (running) {
				try {
					E event = queue.poll(1000, TimeUnit.MILLISECONDS);
					// 事件处理是单线程
					if (event != null) {
						processEvent(event);
					}
				} catch (InterruptedException e) {
					// Nothing to do
				} catch (Exception ex) {
					logger.error(ex, ex);
				}
			}
			logger.warn("Node Inspector stop now.");
		}

		public void stopInspector() {
			this.interrupt();
		}
	}
}
